package com.iot.common.sms;

import com.aliyuncs.CommonRequest;
import com.aliyuncs.CommonResponse;
import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.exceptions.ClientException;
import com.aliyuncs.exceptions.ServerException;
import com.aliyuncs.http.MethodType;
import com.aliyuncs.profile.DefaultProfile;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

/*
 * 阿里云短信服务
 */
@Service
public class AliSmsSender implements SmsSender {

    private static final Logger logger = LoggerFactory.getLogger(AliSmsSender.class);

    @Value("${sms.aliyun.domain}")
    private String domain;// dysmsapi.aliyuncs.com
    @Value("${sms.aliyun.version}")
    private String version;// 2017-05-25
    @Value("${sms.aliyun.regionId}")
    private String regionId;// cn-hangzhou
    @Value("${sms.aliyun.accessKeyId}")
    private String accessKeyId;// LTAInHzzCVSQqe3U
    @Value("${sms.aliyun.accessKeySecret}")
    private String accessKeySecret;// jkB5T6tzEhyk4spxQMDtZWD7s2tkMm
    @Value("${sms.aliyun.signName}")
    private String signName;// SendMsg

    @Override
    public SmsResult send(String PhoneNumbers, String SignName, String TemplateCode, String TemplateParam, String SmsUpExtendCode, String OutId) {
        DefaultProfile profile = DefaultProfile.getProfile(regionId, accessKeyId, accessKeySecret);
        IAcsClient client = new DefaultAcsClient(profile);
        CommonRequest request = new CommonRequest();
        request.setMethod(MethodType.POST);
        request.setDomain(domain);
        request.setVersion(version);
        request.setAction("SendSms");
        request.putQueryParameter("RegionId", regionId);
        request.putQueryParameter("PhoneNumbers", PhoneNumbers);
        request.putQueryParameter("SignName", SignName);
        request.putQueryParameter("TemplateCode", TemplateCode);
        if(StringUtils.isNotEmpty(TemplateParam)){
            request.putQueryParameter("TemplateParam", TemplateParam);
            logger.info("发送短信[ TemplateParam ]：" + TemplateParam);
        }
        if(StringUtils.isNotEmpty(SmsUpExtendCode)){
            request.putQueryParameter("SmsUpExtendCode", SmsUpExtendCode);
        }
        if(StringUtils.isNotEmpty(OutId)){
            request.putQueryParameter("OutId", OutId);
        }
        try {
            CommonResponse response = client.getCommonResponse(request);
            SmsResult smsResult = new SmsResult();
            smsResult.setSuccess(true);
            smsResult.setResult(response);
            logger.info("发送短信[" + TemplateCode + "]：" + response.getData());
            return smsResult;
        } catch (ServerException e) {
            logger.error("发送短信[" + TemplateCode + "]异常" + e.getMessage());
            e.printStackTrace();
        } catch (ClientException e) {
            logger.error("发送短信[" + TemplateCode + "]异常" + e.getMessage());
            e.printStackTrace();
        }
        return null;
    }

    @Override
    public SmsResult sendBatch(String PhoneNumberJson, String SignNameJson, String TemplateCode, String TemplateParamJson, String SmsUpExtendCodeJson) {
        DefaultProfile profile = DefaultProfile.getProfile(regionId, accessKeyId, accessKeySecret);
        IAcsClient client = new DefaultAcsClient(profile);
        CommonRequest request = new CommonRequest();
        request.setMethod(MethodType.POST);
        request.setDomain(domain);
        request.setVersion(version);
        request.setAction("SendBatchSms");
        request.putQueryParameter("RegionId", regionId);
        request.putQueryParameter("PhoneNumberJson", PhoneNumberJson);
        request.putQueryParameter("SignNameJson", SignNameJson);
        request.putQueryParameter("TemplateCode", TemplateCode);
        //request.putQueryParameter("TemplateParamJson", "[{\"date\":\"2019\",\"wea\":\"中雨\",\"tem\":\"25℃~27℃\",\"aircontent\":\"优\"}]");
        if(StringUtils.isNotEmpty(TemplateParamJson)){
            request.putQueryParameter("TemplateParamJson", TemplateParamJson);
            logger.info("批量发送短信[ TemplateParamJson ]：" + TemplateParamJson);
        }
        if(StringUtils.isNotEmpty(SmsUpExtendCodeJson)){
            request.putQueryParameter("SmsUpExtendCodeJson", SmsUpExtendCodeJson);
        }
        try {
            CommonResponse response = client.getCommonResponse(request);
            SmsResult smsResult = new SmsResult();
            smsResult.setSuccess(true);
            smsResult.setResult(response);
            logger.info("批量发送短信[" + TemplateCode + "]：" + response.getData());
            return smsResult;
        } catch (ServerException e) {
            logger.error("批量发送短信[" + TemplateCode + "]异常" + e.getMessage());
            e.printStackTrace();
        } catch (ClientException e) {
            logger.error("批量发送短信[" + TemplateCode + "]异常" + e.getMessage());
            e.printStackTrace();
        }

        return null;
    }

    @Override
    public SmsResult sendWithTemplate(String PhoneNumbers, String SignName, String TemplateCode, String TemplateParam, String SmsUpExtendCode, String OutId) {
        DefaultProfile profile = DefaultProfile.getProfile(regionId, accessKeyId, accessKeySecret);
        IAcsClient client = new DefaultAcsClient(profile);

        CommonRequest request = new CommonRequest();
        request.setMethod(MethodType.POST);
        request.setDomain(domain);
        request.setVersion(version);
        request.setAction("SendSms");
        /*接收短信的手机号码。
        格式：
        国内短信：11位手机号码，例如15951955195。
        国际/港澳台消息：国际区号+号码，例如85200000000。
        支持对多个手机号码发送短信，手机号码之间以英文逗号（,）分隔。上限为1000个手机号码。批量调用相对于单条调用及时性稍有延迟。
        验证码类型短信，建议使用单独发送的方式。*/
        request.putQueryParameter("PhoneNumbers", PhoneNumbers);
        /*短信签名名称。请在控制台签名管理页面签名名称一列查看。
        必须是已添加、并通过审核的短信签名。*/
        request.putQueryParameter("SignName", SignName);
        /*短信模板ID。请在控制台模板管理页面模板CODE一列查看。
        必须是已添加、并通过审核的短信签名；且发送国际/港澳台消息时，请使用国际/港澳台短信模版。*/
        request.putQueryParameter("TemplateCode", TemplateCode);
        /*短信模板变量对应的实际值，JSON格式。
        如果JSON中需要带换行符，请参照标准的JSON协议处理。*/
        if(StringUtils.isNotEmpty(TemplateParam)){
            request.putQueryParameter("TemplateParam", TemplateParam);
        }
        /*上行短信扩展码，无特殊需要此字段的用户请忽略此字段。*/
        if(StringUtils.isNotEmpty(SmsUpExtendCode)){
            request.putQueryParameter("SmsUpExtendCode", SmsUpExtendCode);
        }
        /*外部流水扩展字段。*/
        if(StringUtils.isNotEmpty(OutId)){
            request.putQueryParameter("OutId", OutId);
        }
        try {
            CommonResponse response = client.getCommonResponse(request);
            SmsResult smsResult = new SmsResult();
            smsResult.setSuccess(true);
            smsResult.setResult(response);
            return smsResult;
        } catch (ServerException e) {
            e.printStackTrace();
        } catch (ClientException e) {
            e.printStackTrace();
        }

        return null;
    }

    @Override
    public SmsResult querySendDetail(String PhoneNumber, String SendDate, String PageSize, String CurrentPage, String BizId) {
        DefaultProfile profile = DefaultProfile.getProfile(regionId, accessKeyId, accessKeySecret);
        IAcsClient client = new DefaultAcsClient(profile);

        CommonRequest request = new CommonRequest();
        request.setMethod(MethodType.POST);
        request.setDomain(domain);
        request.setVersion(version);
        request.setAction("QuerySendDetails");
        /*接收短信的手机号码。
        格式：
        国内短信：11位手机号码，例如15900000000。
        国际/港澳台消息：国际区号+号码，例如85200000000。*/
        request.putQueryParameter("PhoneNumber", PhoneNumber);
        /*短信发送日期，支持查询最近30天的记录。
        格式为yyyyMMdd，例如20181225。*/
        request.putQueryParameter("SendDate", SendDate);
        /*分页查看发送记录，指定每页显示的短信记录数量。
        取值范围为1~50。*/
        request.putQueryParameter("PageSize", PageSize);
        //分页查看发送记录，指定发送记录的的当前页码
        request.putQueryParameter("CurrentPage", CurrentPage);
        //发送回执ID，即发送流水号。调用发送接口SendSms或SendBatchSms发送短信时，返回值中的BizId字段。
        request.putQueryParameter("BizId", BizId);

        try {
            CommonResponse response = client.getCommonResponse(request);
            SmsResult smsResult = new SmsResult();
            smsResult.setSuccess(true);
            smsResult.setResult(response);
            return smsResult;
        } catch (ServerException e) {
            e.printStackTrace();
        } catch (ClientException e) {
            e.printStackTrace();
        }
        return null;
    }


    public String getDomain() {
        return domain;
    }

    public void setDomain(String domain) {
        this.domain = domain;
    }

    public String getVersion() {
        return version;
    }

    public void setVersion(String version) {
        this.version = version;
    }

    public String getRegionId() {
        return regionId;
    }

    public void setRegionId(String regionId) {
        this.regionId = regionId;
    }

    public String getAccessKeyId() {
        return accessKeyId;
    }

    public void setAccessKeyId(String accessKeyId) {
        this.accessKeyId = accessKeyId;
    }

    public String getAccessKeySecret() {
        return accessKeySecret;
    }

    public void setAccessKeySecret(String accessKeySecret) {
        this.accessKeySecret = accessKeySecret;
    }

    public String getSignName() {
        return signName;
    }

    public void setSignName(String signName) {
        this.signName = signName;
    }
}